#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2019/10/14 10:48
# @Author  : ZRD
# @File    : webserver.py.py
import json, sys
from apps.bottle import run, route, request
from schema import Regex, And, Use, Optional, Schema, Hook
from apps.db import Sqlite3cls
from .log import LOGGER


@route('/task/create', method="post")
def task_create():
    check_data = {
        "task_name": Regex("[a-zA-Z0-9_]{1,255}", error="task_name应1-255位字母、数字、下划线组成"),
        Optional("taskid"): And(int, lambda x: 0 < x, error="taskid应大于0整数"),
        Optional("pre_ommand", default=""): Use(str, error="应字符串"),
        Optional("post_ommand", default=""): Use(str, error="应字符串"),
        Optional("workdir", default="."): Use(str, error="应字符串"),
    }

    try:
        res = Schema(check_data).validate(request.json)
        with Sqlite3cls() as ss:
            task_name = res.get("task_name")
            hastask = ss.task_get_by_task_name(task_name)

            if hastask > 0:
                raise ValueError(f"任务: {task_name} 已经正在运行.")
            if int(ss.task_count()) > 5:
                raise ValueError("超出任务并行数量:5")
            isok, msg = ss.task_create(res)
            if not isok:
                raise ValueError(msg)
        respdata = {"status": 0, "errmsg": "ok"}

    except Exception as e:
        _, exc_value, _ = sys.exc_info()
        LOGGER.error(f"请求错误:{exc_value}")
        respdata = {"status": 1, "errmsg": str(exc_value)}

    return respdata


# todo
@route('/task/kill', method="post")
def task_create():
    respdata = {"status": 0, "errmsg": "结束任务todo"}

    return respdata


# todo
@route('/task/list', method="post")
def task_create():
    respdata = {"status": 0, "errmsg": "任务列表todo"}

    return respdata


# pingpong 存活探测
@route('/agent/ping', method="get")
def task_create():
    respdata = {"status": 0, "data": "pong"}
    return respdata






def runserver(ipaddr='0.0.0.0', port=5551, debug=True):
    run(host=ipaddr, port=port, debug=debug)
